package main

import (
	"exam/db"
	"github.com/gin-gonic/gin"
	"strconv"
)

func main() {
	r := gin.Default()
	r.GET("/api/exams", func(c *gin.Context) {
		arr, err := db.Rand(10)
		if err != nil {
			c.JSON(200, gin.H{"exams": arr, "error": err})
			return
		}
		c.JSON(200, gin.H{
			"exams": arr,
			"error": nil,
		})
	})
	r.POST("/api/exams", func(c *gin.Context) {
		var exam db.Exam
		err := c.BindJSON(&exam)
		if err != nil {
			c.JSON(200, gin.H{"status": "bad request"})
			return
		}
		err = db.Save(&exam)
		if err != nil {
			c.JSON(200, gin.H{"status": "题目保存失败"})
			return
		}
		c.JSON(200, gin.H{"status": "题目已保存"})
	})
	r.DELETE("/api/exams/:id", func(c *gin.Context) {
		if c.Query("pw") != "zxcvbnm" {
			c.JSON(200, gin.H{"status": "authentication failed"})
			return
		}
		id, err := strconv.Atoi(c.Param("id"))
		if err != nil {
			c.JSON(200, gin.H{"status": "bad request"})
			return
		}
		err = db.Delete(int64(id))
		if err != nil {
			c.JSON(200, gin.H{"status": "删除失败", "error": err})
			return
		}
		c.JSON(200, gin.H{"status": "删除成功"})
	})
	r.GET("/", func(c *gin.Context) {
		c.File("./index.html")
	})
	r.Run(":8080")
}
